package com.int_tech.mession.controller;

import com.int_tech.MessageCodeAll.dao.CodeA0Dao;
import com.int_tech.MessageCodeAll.dao.CodeA0NewDao;
import com.int_tech.MessageCodeAll.entity.CodeA0;
import com.int_tech.MessageCodeAll.entity.CodeA0New;
import com.int_tech.car.dao.CarDao;
import com.int_tech.car.dao.CityDao;
import com.int_tech.car.entity.Car;
import com.int_tech.car.entity.City;
import com.int_tech.control.dao.SocketLogSendDao;
import com.int_tech.control.entity.SocketLogSend;
import com.int_tech.mession.dao.MessionDao;
import com.int_tech.mession.entity.Mession;
import com.int_tech.station.dao.StationDao;
import com.int_tech.station.entity.Station;
import com.int_tech.user.dao.UserDao;
import com.int_tech.user.entity.Client;
import com.int_tech.user.entity.User;
import com.int_tech.utils.*;
import com.int_tech.utils.poiOut.MessionPoi;
import com.int_tech.utils.poiOut.UserPoi;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by liubch on 2017/10/15.
 */
@Controller
@RequestMapping("mession")
public class MessionController {

    @Autowired
    private CarDao carDao;

    @Autowired
    private MessionDao messionDao;

    @Autowired
    private CityDao cityDao;

    @Autowired
    private SocketLogSendDao socketLogSendDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private StationDao stationDao;

    @Autowired
    private CodeA0Dao codeA0Dao;

    @Autowired
    private CodeA0NewDao codeA0NewDao;


    /**
     * 查询任务清单
     * @param model
     * @param request
     * @return
     */
//    @RequestMapping(value = "/messionList", method = RequestMethod.GET)
    @GetMapping("messionList")
    public String messionList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                          @RequestParam(value = "size", defaultValue = "8") Integer size,
                          Model model, HttpServletRequest request) {
//    public String messionList(Model model, HttpServletRequest request) {

//        int clientId = (int) request.getSession().getAttribute("uid");



        int clientId = -99;

        try
        {
            clientId = (int) request.getSession().getAttribute("uid");
        }
        catch (Exception e)
        {
            return "car/retry";
        }
        PageRequest pageRequest = new PageRequest(page - 1, size);
        Page<Mession> messionPage = null;

        List<Car> carList = new ArrayList<>();

        if(clientId == 1)
        {
            carList = carDao.findAll();
        }
        else
        {
            carList = carDao.findCarByClientIdAndIsDel(clientId,0);


            if(carList == null || carList.size() == 0)
            {
                User user = userDao.findById(clientId);

                String stationsa[];

                //一个用户多个场站
                if(user.getStationId().contains(","))
                {
                    List<Station> stationList = new ArrayList<>();

                    stationsa = user.getStationId().split(",");

                    for(String sid : stationsa)
                    {
                        Station station = stationDao.findById(Integer.parseInt(sid));

                        carList.addAll(carDao.findCarByStationIdAndIsDel(station.getId(),0));
                    }
                }
                else
                {
                    Station station = stationDao.findById(Integer.parseInt(user.getStationId()));

                    carList = new ArrayList<>();

                    carList = carDao.findCarByStationIdAndIsDel(station.getId(),0);
                }
            }
        }

        List<String> numbers = new ArrayList<>();

        for (Car car:carList) {
            numbers.add(car.getCarNumber());
        }

        messionPage = messionDao.findByCarNumberInAndIsOverAndYiChangAndCheckStatusOrderByCreateTimeDesc(numbers,1,0,3,pageRequest);

        List<Mession> messionList = messionPage.getContent();

        List<Mession> messionList1 = new ArrayList<>();

        List<City> cityList = cityDao.findAll();

        for (Mession mession : messionList)
        {
            try
            {
                String rate = mession.getRate();

                Double d = Double.parseDouble(rate);

                String r = String.format("%.1f", d).toString();
                mession.setRate(r);
                for (City city : cityList)
                {
                    if(mession.getCarNumber().startsWith(city.getCityNumber()))
                    {
                        String number = mession.getCarNumber().substring(3,9);
                        mession.setCarNumber(city.getCity()+number);
                        break;
                    }
                }


                if("0".equals(rate))
                {

                }
                else
                {
                    messionList1.add(mession);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }


        model.addAttribute("messionList",messionList);

        model.addAttribute("word","");

        model.addAttribute("createTime","");

        model.addAttribute("endTime","");

        model.addAttribute("typefont", "1");
        model.addAttribute("currentPage", page);
        model.addAttribute("size", size);
        model.addAttribute("maxSize", messionPage.getTotalPages());

        return "/mession/messionList";
    }

    @RequestMapping("choose")
    public String choose(@RequestParam(value = "page", defaultValue = "1") Integer page,
                         @RequestParam(value = "size", defaultValue = "10") Integer size,
                         @RequestParam(value = "word") String word, Model model, HttpServletRequest request) {
        int clientId = (int) request.getSession().getAttribute("uid");
        PageRequest pageRequest = new PageRequest(page - 1, size);
        Page<Mession> messionPage = null;

        List<Car> carList = new ArrayList<>();

        if(clientId == 1)
        {
            carList = carDao.findAll();
        }
        else
        {
            carList = carDao.findCarByClientIdAndIsDel(clientId,0);


            if(carList == null || carList.size() == 0)
            {
                User user = userDao.findById(clientId);

                String stationsa[];

                //一个用户多个场站
                if(user.getStationId().contains(","))
                {
                    List<Station> stationList = new ArrayList<>();

                    stationsa = user.getStationId().split(",");

                    for(String sid : stationsa)
                    {
                        Station station = stationDao.findById(Integer.parseInt(sid));

                        carList.addAll(carDao.findCarByStationIdAndIsDel(station.getId(),0));
                    }
                }
                else
                {
                    Station station = stationDao.findById(Integer.parseInt(user.getStationId()));

                    carList = new ArrayList<>();

                    carList = carDao.findCarByStationIdAndIsDel(station.getId(),0);
                }
            }
        }

        List<String> numbers = new ArrayList<>();

        for (Car car:carList) {
            numbers.add(car.getCarNumber());
        }

        messionPage = messionDao.findByCarNumberInAndIsOverAndYiChangAndCheckStatus(numbers,1,0,3,pageRequest);

        List<Mession> messionList = messionPage.getContent();

        List<Mession> messionList1 = new ArrayList<>();

        List<City> cityList = cityDao.findAll();

        for (Mession mession : messionList)
        {
            try
            {
                String rate = mession.getRate();

                Double d = Double.parseDouble(rate);

                String r = String.format("%.1f", d).toString();
                mession.setRate(r);
                for (City city : cityList)
                {
                    if(mession.getCarNumber().startsWith(city.getCityNumber()))
                    {
                        String number = mession.getCarNumber().substring(3,9);
                        mession.setCarNumber(city.getCity()+number);
                        break;
                    }
                }


                if("0".equals(rate))
                {

                }
                else
                {
                    messionList1.add(mession);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }

        model.addAttribute("messionList",messionList);

        model.addAttribute("word","");

        model.addAttribute("createTime","");

        model.addAttribute("endTime","");

        model.addAttribute("typefont", "2");
        model.addAttribute("currentPage", page-1);
        model.addAttribute("size", size);
        model.addAttribute("maxSize", messionPage.getTotalPages());


        return "/mession/messionList";
    }


    /**
     * TODO ex导出
     *
     * @param
     * @return
     * @author dmy
     */
    @RequestMapping("messionExout")
    public void messionExout(HttpServletResponse response, @RequestParam(value = "word") String word,HttpServletRequest request) {

        String createTime = (String)request.getSession().getAttribute("crtime");
        String endTime = (String)request.getSession().getAttribute("edtime");
        if(StringUtils.isEmpty(createTime))
        {
            createTime = DateTool.Date2String(new Date(),"yyyy-MM-dd 00:00:00");
        }
        else
        {
            createTime = createTime.split(" ")[0]+" 00:00:00";
        }

        if(StringUtils.isEmpty(endTime))
        {
            endTime = DateTool.Date2String(new Date(),"yyyy-MM-dd 23:59:59");
        }
        else
        {
            endTime = endTime.split(" ")[0]+" 23:59:59";
        }
        Date cdate = DateTool.string2Date(createTime,"yyyy-MM-dd HH:mm:ss");
        Date edate = DateTool.string2Date(endTime,"yyyy-MM-dd HH:mm:ss");
        List<Mession> messionList = messionDao.findByIsOverAndCreateTimeAfterAndCreateTimeBeforeAndYiChangAndCheckStatus(1,cdate,edate,0,3);
        List<Mession> outMessionList = new ArrayList<>();

        if(StringUtils.isEmpty(word))
        {
            outMessionList = messionList;
        }
        else
        {
            for (Mession mession:messionList)
            {
                if(mession.toString().contains(word))
                {
                    outMessionList.add(mession);
                }
            }
        }

        MessionPoi.messionPoi(outMessionList, response);
    }

    @RequestMapping(value = "/findMession", method = RequestMethod.POST)
    public String findMession(@RequestParam(value = "page", defaultValue = "1") Integer page,
                         @RequestParam(value = "size", defaultValue = "10") Integer size,
                         @RequestParam(value = "word") String word, Model model, @RequestParam(value = "createTime")String createTime,@RequestParam(value = "endTime")String endTime,HttpServletRequest request) {

        PageRequest pageRequest = new PageRequest(page - 1, size);
        Page<Mession> messionPage = null;

        try
        {
            if(StringUtils.isNotEmpty(word))
            {
                word = word.toUpperCase();
            }

            if(StringUtils.isEmpty(createTime))
            {
                createTime = DateTool.Date2String(new Date(),"yyyy-MM-dd 00:00:00");
            }
            else
            {
                request.getSession().setAttribute("crtime",createTime);
                createTime = createTime.split(" ")[0]+" 00:00:00";
            }

            if(StringUtils.isEmpty(endTime))
            {
                endTime = DateTool.Date2String(new Date(),"yyyy-MM-dd 23:59:59");
            }
            else
            {
                request.getSession().setAttribute("edtime",endTime);
                endTime = endTime.split(" ")[0]+" 23:59:59";
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        int clientId = (int) request.getSession().getAttribute("uid");

        List<Car> carList = new ArrayList<>();

        if(clientId == 1)
        {
            carList = carDao.findAll();
        }
        else
        {
            carList = carDao.findCarByClientIdAndIsDel(clientId,0);

            if(carList == null || carList.size() == 0)
            {
                User user = userDao.findById(clientId);

                Station station = stationDao.findById(Integer.parseInt(user.getStationId()));

                carList = new ArrayList<>();

                carList = carDao.findCarByStationIdAndIsDel(station.getId(),0);
            }
        }

        List<String> numbers = new ArrayList<>();

        for (Car car:carList) {
            numbers.add(car.getCarNumber());
        }


        Date cdate = DateTool.string2Date(createTime,"yyyy-MM-dd HH:mm:ss");
        Date edate = DateTool.string2Date(endTime,"yyyy-MM-dd HH:mm:ss");

//        messionPage = messionDao.findByCarNumberInAndCreateTimeAfterAndCreateTimeBeforeAndIsOverAndYiChangAndCheckStatus(numbers,cdate,edate,1,0,3,pageRequest);

        List<Mession> messionList = messionDao.findByCarNumberInAndCreateTimeAfterAndCreateTimeBeforeAndIsOverAndYiChangAndCheckStatus(numbers,cdate,edate,1,0,3);

        List<Mession>   messionList1 = new ArrayList<>();

        List<City> cityList = cityDao.findAll();

        for(Mession mession : messionList)
        {
            if(mession.getCarNumber().contains(word))
            {
                for (City city : cityList)
                {
                    if(mession.getCarNumber().startsWith(city.getCityNumber()))
                    {
                        String number = mession.getCarNumber().substring(3,9);
                        mession.setCarNumber(city.getCity()+number);
                        break;
                    }
                }
                messionList1.add(mession);
            }
        }

        model.addAttribute("messionList",messionList1);

        model.addAttribute("word",word);
        model.addAttribute("createTime",createTime.split(" ")[0]);
        model.addAttribute("endTime",endTime.split(" ")[0]);

        model.addAttribute("typefont", "3");


        return "/mession/messionList";
    }


    /**
     * 通过messionId获取装载率数据
     * @param request
     * @param messionId
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/getMessionRateByMessionId", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String checkSocketLog(HttpServletRequest request,int messionId,HttpServletResponse response) throws UnsupportedEncodingException {

//        KuaYu.kuaYuResponse(response);

        Mession mession = messionDao.findById(messionId);

        CodeA0New codeA0New = codeA0NewDao.findByDataStringLike(mession.getRateDataString());


        int h = Integer.parseInt(codeA0New.getDataString().split(",")[13]);
        int l = Integer.parseInt(codeA0New.getDataString().split(",")[14]);


        String[] rateData = mession.getRateDataString().split(",");

        int t = h*l;
        String[] threeD = new String[t];

        int n = 0;

        for (int i = 0; i < l; i++)
        {
            for (int j=0;j<h;j++)
            {
                float zz = Float.parseFloat(rateData[n]);

                zz = zz/10;

                String zzz = String.valueOf(zz);
                threeD[n] = "{x:"+i+",y:"+j+",z:"+zzz+"}";
                n++;
            }
        }

        System.out.print(threeD);

        JSONObject object = new JSONObject();
        object.put("dataString", threeD);


        //获取车辆信息
        Car car = carDao.findCarByCarNumberAndIsDel(mession.getCarNumber(),0);

        String carHeight = car.getHeight();

        Float intHeight = Float.valueOf(carHeight) * 100;

        object.put("carHeight", intHeight);


        return object.toString();
    }



    /**
     * 通过messionId获取装载率数据
     * @param request
     * @param mid
     * @return
     * @throws UnsupportedEncodingException
     */
    @ResponseBody
    @RequestMapping(value = "/getPostMessionRateByMessionId", method = RequestMethod.POST,produces="application/json")
    public String getPostMessionRateByMessionId(String mid,HttpServletRequest request, HttpServletResponse response,String timeStamp,String noncestr,String appId,String sign) throws UnsupportedEncodingException, NoSuchAlgorithmException {

        KuaYu.kuaYuResponse(response);

        //验签
        //获取appSecret
        String appSecret = "7Bque02CylCt3Go20bktTfiSlYTfEPX7";

        JSONObject jsonObject = new JSONObject();

        String code = "-1";
        String msg = "";

        if ("验证签名失败".equals(appSecret)) {
            //返回验证失败
            msg = appSecret;
        } else {
            //继续验证加密
            String md5Message = EncoderByMd5.EncoderByMd5(appId+appSecret+timeStamp+noncestr);

            System.out.print(md5Message);

            if (sign.equals(md5Message)) {
                //签名正确，继续
                //返回签名成功
                code = "1";
                msg = "签名正确";
            } else {
                //返回验签失败
                msg = appSecret;
            }
        }

        jsonObject.put("code", code);
        jsonObject.put("msg", msg);

        if("1".equals(code))
        {

            CodeA0New codeA0NewOut = codeA0NewDao.findByOpenNumber(mid);

            if(codeA0NewOut == null)
            {
                codeA0NewOut = codeA0NewDao.findByCloseNumber(mid);
            }

//            CodeA0 codeA0 = codeA0Dao.findByDataStringLike(mession.getRateDataString());


            int h = Integer.parseInt(codeA0NewOut.getHang());
            int l = Integer.parseInt(codeA0NewOut.getLie());


            String[] rateData = codeA0NewOut.getRateDateString().split(",");

            int t = h*l;
            String[] threeD = new String[t];

            int n = 0;

            for (int i = 0; i < l; i++)
            {
                for (int j=0;j<h;j++)
                {
                    float zz = Float.parseFloat(rateData[n]);

                    zz = zz/10;

                    String zzz = String.valueOf(zz);
                    threeD[n] = "{x:"+i+",y:"+j+",z:"+zzz+"}";
                    n++;
                }
            }

            System.out.print(threeD);

            JSONObject object = new JSONObject();
            object.put("dataString", threeD);


            //获取车辆信息
//        Car car = carDao.findCarByCarNumberAndIsDel(mession.getCarNumber(),0);

            String carHeight = codeA0NewOut.getHeight();

            Float intHeight = Float.valueOf(carHeight) * 100;

            object.put("carHeight", intHeight);
            object.put("code",code);

            return object.toString();
        }
        else
        {
            JSONObject object = new JSONObject();
            object.put("code",code);
            return object.toString();
        }
    }

}
